// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {

    // 返回顶部按钮
    const backToTopButton = document.getElementById('back-to-top');

    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            backToTopButton.classList.remove('opacity-0', 'invisible');
            backToTopButton.classList.add('opacity-100', 'visible');
        } else {
            backToTopButton.classList.add('opacity-0', 'invisible');
            backToTopButton.classList.remove('opacity-100', 'visible');
        }
    });

    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });

    // 平滑滚动
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();

            const targetId = this.getAttribute('href');
            if (targetId === '#') return;

            const targetElement = document.querySelector(targetId);
            if (targetElement) {
                targetElement.scrollIntoView({
                    behavior: 'smooth'
                });
            }
        });
    });

    // 导航栏滚动效果
    const header = document.querySelector('header');
    let lastScrollTop = 0;

    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;

        if (scrollTop > 100) {
            header.classList.add('shadow-md');
            header.classList.remove('shadow-sm');
        } else {
            header.classList.remove('shadow-md');
            header.classList.add('shadow-sm');
        }

        lastScrollTop = scrollTop;
    });

    // 登录注册模态框控制
    const loginModal = document.getElementById('login-modal');
    const registerModal = document.getElementById('register-modal');
    const loginLink = document.getElementById('login-link');
    const registerLink = document.getElementById('register-link');
    const mobileLoginLink = document.getElementById('mobile-login-link');
    const mobileRegisterLink = document.getElementById('mobile-register-link');
    const heroRegisterBtn = document.getElementById('hero-register-btn');
    const closeLogin = document.getElementById('close-login');
    const closeRegister = document.getElementById('close-register');
    const switchToRegister = document.getElementById('switch-to-register');
    const switchToLogin = document.getElementById('switch-to-login');

    function openLoginModal() {
        loginModal.classList.remove('opacity-0', 'invisible');
        loginModal.querySelector('.scale-95').classList.remove('scale-95');
        loginModal.querySelector('.scale-100').classList.add('scale-100');
        document.body.style.overflow = 'hidden';
    }

    function closeLoginModal() {
        loginModal.classList.add('opacity-0', 'invisible');
        loginModal.querySelector('.scale-100').classList.remove('scale-100');
        loginModal.querySelector('.scale-95').classList.add('scale-95');
        document.body.style.overflow = '';
        // 重置表单
        document.getElementById('login-form').reset();
        hideLoginErrors();
    }

    function openRegisterModal() {
        registerModal.classList.remove('opacity-0', 'invisible');
        registerModal.querySelector('.scale-95').classList.remove('scale-95');
        registerModal.querySelector('.scale-100').classList.add('scale-100');
        document.body.style.overflow = 'hidden';
    }

    function closeRegisterModal() {
        registerModal.classList.add('opacity-0', 'invisible');
        registerModal.querySelector('.scale-100').classList.remove('scale-100');
        registerModal.querySelector('.scale-95').classList.add('scale-95');
        document.body.style.overflow = '';
        // 重置表单
        document.getElementById('register-form').reset();
        hideRegisterErrors();
    }

    function hideLoginErrors() {
        document.getElementById('login-email-error').classList.add('hidden');
        document.getElementById('login-password-error').classList.add('hidden');
    }

    function hideRegisterErrors() {
        document.getElementById('register-name-error').classList.add('hidden');
        document.getElementById('register-email-error').classList.add('hidden');
        document.getElementById('register-password-error').classList.add('hidden');
        document.getElementById('register-confirm-password-error').classList.add('hidden');
    }

    // 打开登录模态框
    loginLink.addEventListener('click', openLoginModal);
    mobileLoginLink.addEventListener('click', function() {
        openLoginModal();
    });

    // 打开注册模态框
    registerLink.addEventListener('click', openRegisterModal);
    mobileRegisterLink.addEventListener('click', function() {
        openRegisterModal();
    });
    if (heroRegisterBtn) {
        heroRegisterBtn.addEventListener('click', openRegisterModal);
    }

    // 关闭模态框
    closeLogin.addEventListener('click', closeLoginModal);
    closeRegister.addEventListener('click', closeRegisterModal);

    // 切换到注册
    switchToRegister.addEventListener('click', function() {
        closeLoginModal();
        setTimeout(openRegisterModal, 300);
    });

    // 切换到登录
    switchToLogin.addEventListener('click', function() {
        closeRegisterModal();
        setTimeout(openLoginModal, 300);
    });

    // 点击模态框外部关闭
    loginModal.addEventListener('click', function(e) {
        if (e.target === loginModal) {
            closeLoginModal();
        }
    });

    registerModal.addEventListener('click', function(e) {
        if (e.target === registerModal) {
            closeRegisterModal();
        }
    });

    // 登录表单验证
    document.getElementById('login-form').addEventListener('submit', function(e) {
        e.preventDefault();
        let isValid = true;
        hideLoginErrors();

        const email = document.getElementById('login-email').value.trim();
        const password = document.getElementById('login-password').value;

        // 验证邮箱
        if (!email) {
            document.getElementById('login-email-error').textContent = '请输入邮箱';
            document.getElementById('login-email-error').classList.remove('hidden');
            isValid = false;
        } else if (!/\S+@\S+\.\S+/.test(email)) {
            document.getElementById('login-email-error').textContent = '请输入有效的邮箱地址';
            document.getElementById('login-email-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证密码
        if (!password) {
            document.getElementById('login-password-error').textContent = '请输入密码';
            document.getElementById('login-password-error').classList.remove('hidden');
            isValid = false;
        } else if (password.length < 8) {
            document.getElementById('login-password-error').textContent = '密码长度至少为8位';
            document.getElementById('login-password-error').classList.remove('hidden');
            isValid = false;
        }

        if (isValid) {
            // 模拟登录API请求
            simulateLogin(email, password);
        }
    });

    // 注册表单验证
    document.getElementById('register-form').addEventListener('submit', function(e) {
        e.preventDefault();
        let isValid = true;
        hideRegisterErrors();

        const name = document.getElementById('register-name').value.trim();
        const email = document.getElementById('register-email').value.trim();
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('register-confirm-password').value;

        // 验证姓名
        if (!name) {
            document.getElementById('register-name-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证邮箱
        if (!email) {
            document.getElementById('register-email-error').textContent = '请输入邮箱';
            document.getElementById('register-email-error').classList.remove('hidden');
            isValid = false;
        } else if (!/\S+@\S+\.\S+/.test(email)) {
            document.getElementById('register-email-error').textContent = '请输入有效的邮箱地址';
            document.getElementById('register-email-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证密码
        if (!password) {
            document.getElementById('register-password-error').textContent = '请输入密码';
            document.getElementById('register-password-error').classList.remove('hidden');
            isValid = false;
        } else if (password.length < 8) {
            document.getElementById('register-password-error').textContent = '密码长度至少为8位';
            document.getElementById('register-password-error').classList.remove('hidden');
            isValid = false;
        } else if (!/[A-Za-z]/.test(password) || !/[0-9]/.test(password)) {
            document.getElementById('register-password-error').textContent = '密码需包含字母和数字';
            document.getElementById('register-password-error').classList.remove('hidden');
            isValid = false;
        }

        // 验证确认密码
        if (!confirmPassword) {
            document.getElementById('register-confirm-password-error').textContent = '请确认密码';
            document.getElementById('register-confirm-password-error').classList.remove('hidden');
            isValid = false;
        } else if (confirmPassword !== password) {
            document.getElementById('register-confirm-password-error').classList.remove('hidden');
            isValid = false;
        }

        if (isValid) {
            // 模拟注册API请求
            simulateRegister(name, email, password);
        }
    });

    // 密码显示/隐藏切换
    document.getElementById('toggle-login-password').addEventListener('click', function() {
        const passwordInput = document.getElementById('login-password');
        const icon = document.getElementById('login-password-icon');

        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });

    document.getElementById('toggle-register-password').addEventListener('click', function() {
        const passwordInput = document.getElementById('register-password');
        const icon = document.getElementById('register-password-icon');

        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });

    document.getElementById('toggle-register-confirm-password').addEventListener('click', function() {
        const passwordInput = document.getElementById('register-confirm-password');
        const icon = document.getElementById('register-confirm-password-icon');

        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        }
    });

    // 显示通知
    function showNotification(title, message, type = 'success') {
        const notification = document.getElementById('notification');
        const notificationTitle = document.getElementById('notification-title');
        const notificationMessage = document.getElementById('notification-message');
        const notificationIcon = document.getElementById('notification-icon');

        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 设置图标和颜色
        if (type === 'success') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-green-100 flex items-center justify-center text-green-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-check"></i>';
        } else if (type === 'error') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-red-100 flex items-center justify-center text-red-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-times"></i>';
        } else if (type === 'warning') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-yellow-100 flex items-center justify-center text-yellow-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-exclamation-triangle"></i>';
        } else if (type === 'info') {
            notificationIcon.className = 'flex-shrink-0 w-6 h-6 rounded-full bg-blue-100 flex items-center justify-center text-blue-500 mr-3';
            notificationIcon.innerHTML = '<i class="fas fa-info-circle"></i>';
        }

        // 显示通知
        notification.classList.remove('translate-x-full');

        // 3秒后自动关闭
        setTimeout(() => {
            closeNotification();
        }, 3000);
    }

    // 关闭通知
    function closeNotification() {
        const notification = document.getElementById('notification');
        notification.classList.add('translate-x-full');
    }

    document.getElementById('close-notification').addEventListener('click', closeNotification);

    // 模拟登录API请求
    function simulateLogin(email, password) {
        // 显示加载状态
        const loginButton = document.getElementById('login-form').querySelector('button[type="submit"]');
        const originalText = loginButton.innerHTML;
        loginButton.disabled = true;
        loginButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> 登录中...';

        // 模拟API请求延迟
        setTimeout(() => {
            // 恢复按钮状态
            loginButton.disabled = false;
            loginButton.innerHTML = originalText;

            // 模拟登录成功
            showNotification('登录成功', '欢迎回来，您已成功登录！');
            closeLoginModal();

            // 在实际应用中，这里应该进行实际的API调用并处理响应
            // fetch('/api/login', {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify({ email, password })
            // })
            // .then(response => response.json())
            // .then(data => {
            //     if (data.success) {
            //         showNotification('登录成功', '欢迎回来，您已成功登录！');
            //         closeLoginModal();
            //     } else {
            //         showNotification('登录失败', data.message, 'error');
            //     }
            // })
            // .catch(error => {
            //     showNotification('登录失败', '网络错误，请稍后重试', 'error');
            // });
        }, 1500);
    }

    // 模拟注册API请求
    function simulateRegister(name, email, password) {
        // 显示加载状态
        const registerButton = document.getElementById('register-form').querySelector('button[type="submit"]');
        const originalText = registerButton.innerHTML;
        registerButton.disabled = true;
        registerButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> 注册中...';

        // 模拟API请求延迟
        setTimeout(() => {
            // 恢复按钮状态
            registerButton.disabled = false;
            registerButton.innerHTML = originalText;

            // 模拟注册成功
            showNotification('注册成功', '恭喜您注册成功，请查收验证邮件！');
            closeRegisterModal();

            // 在实际应用中，这里应该进行实际的API调用并处理响应
            // fetch('/api/register', {
            //     method: 'POST',
            //     headers: {
            //         'Content-Type': 'application/json'
            //     },
            //     body: JSON.stringify({ name, email, password })
            // })
            // .then(response => response.json())
            // .then(data => {
            //     if (data.success) {
            //         showNotification('注册成功', '恭喜您注册成功，请查收验证邮件！');
            //         closeRegisterModal();
            //     } else {
            //         showNotification('注册失败', data.message, 'error');
            //     }
            // })
            // .catch(error => {
            //     showNotification('注册失败', '网络错误，请稍后重试', 'error');
            // });
        }, 1500);
    }
});